<?php

namespace Yolo\Service;

use Swoole\Http\Request;

/**
 * RPC请求对象
 * @author LUSHAOMING
 * @date 2024-10-20
 */
class RpcRequest
{
    protected Request $swooleRequest;

    public array $requestData;

    public function __construct(Request $swooleRequest, array $requestData)
    {
        $this->swooleRequest = $swooleRequest;
        $this->requestData = $requestData;
    }

    public function getSwooleRequest(): Request
    {
        return $this->swooleRequest;
    }

    public function getEndpoint(): string
    {
        return $this->requestData['endpoint'] ?? '';
    }

    /**
     * 获取请求body
     * @return array
     */
    public function getBody(): array
    {
        return $this->requestData['body'] ?? [];
    }

    /**
     * 获取metadata
     * @return array
     */
    public function getMetadata(): array
    {
        return $this->requestData['metadata'] ?? [];
    }

    /**
     * 获取路径上的参数（仅restful接口有效）
     * @return array|null
     */
    public function getPathArguments(): ?array
    {
        return $this->requestData['path'] ?? null;
    }

    /**
     * 获取QS的参数（仅restful接口有效）
     * @return array|null
     */
    public function getQueryArguments(): ?array
    {
        return $this->requestData['qs'] ?? null;
    }

    /**
     * 获取所有请求头
     * @return array
     */
    public function getHeaders(): array
    {
        return $this->requestData['headers'] ?? [];
    }

    /**
     * 获取指定名称的请求头
     * @param string $name
     * @return string|null
     */
    public function getHeader(string $name): ?string
    {
        return $this->requestData['headers'][$name] ?? null;
    }

    /**
     * 获取所有Cookie
     * @return array
     */
    public function getCookies(): array
    {
        return $this->requestData['cookies'] ?? [];
    }

    /**
     * 获取指定名称的Cookie
     * @param string $name cookie名称
     * @return string|null 如果存在，返回相应的cookie；如果没有，返回null
     */
    public function getCookie(string $name): ?string
    {
        return $this->requestData['cookies'][$name] ?? null;
    }

    /**
     * 从metadata信息里获取merchant ID
     * @return int|null
     */
    public function getMerchantIdFromMetadata(): ?int
    {
        return $this->requestData['metadata']['merchant'] ?? null;
    }

    /**
     * 从metadata信息里获取用户ID
     * @return int|null
     */
    public function getUserIdFromMetadata(): ?int
    {
        return $this->requestData['metadata']['userId'] ?? null;
    }

    /**
     * 从metadata信息里获取客户端IP
     * @return int|null
     */
    public function getClientIpFromMetadata(): ?int
    {
        return $this->requestData['metadata']['clientIp'] ?? null;
    }

    /**
     * 从metadata信息里获取权限信息
     * @return array
     */
    public function getPermissionsFromMetadata(): array
    {
        return $this->requestData['metadata']['permissions'] ?? [];
    }
}
